var path = require('path');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var winston = require('winston');


var myQuery = function(connection, queryString){
	return new Promise(function(resolve, reject){
		connection.query(queryString, function(err, rows){
			if(err){
				reject(err);
			}else{
				resolve(rows);
			}
		});
	});
}
module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var template = 'ld/' + eventId;
	var pathToTemplate = path.join(__dirname,'..', 'templates/ld', eventId + '.ejs');
	var pathToConfig = path.join(__dirname, '..', 'events', eventId, 'config.json');
	var queryWinners = 'SELECT COUNT(*) as winners FROM luckydraw WHERE state="win" AND event_id=' + eventId;
	Promise.join(fs.readFileAsync(pathToConfig), fs.readFileAsync(pathToTemplate), function(config, tpl){
		if(config){
			config = config.toString();
			pool.getConnection(function(err, connection){
				if(err){
					winston.error(err);
					res.end();
				}else{
					myQuery(connection, queryWinners)
						.then(function(rows){
							var winners = rows[0].winners;
							res.render(template, {data: {config:config, winners:winners, eventId: eventId}});
						}).catch(function(err){
							winston.error(err);
							res.end();
						});
					connection.release();
				}
			});
		}else{
			res.end();
		}
			
		
	}).catch(function(err){
		winston.error(err);
		res.end();
	});
	
}
